package com.lxiaodd.handler;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lxiaodd.util.AESUtil;

/**
 * 过滤器,使用代理类替换request 及response
 * 实现传入参数解密接返回值加密
 * @author liupeng
 *
 */
public class HttpServletFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println(request.getContentType());
		MyRequestWrapper requestWrapper = null;
		MyResponseWrapper responseWrapper =null;
        if(request instanceof HttpServletRequest) {
        	//修改request 解密传入参数
            requestWrapper = new MyRequestWrapper((HttpServletRequest) request);
            String body = requestWrapper.getRequestBodyStr();
    		String decodeBody =null;
			try {
				decodeBody = AESUtil.decrypt(body, AESUtil.KEY);
			} catch (Exception e) {
				e.printStackTrace();
				decodeBody = body;
			}
			String contentType = request.getContentType().toLowerCase();
			if(contentType.startsWith("application/json")){
				//json数据 @RequestBody
				requestWrapper.setRequestBodyStr(decodeBody);
			}
			if(contentType.startsWith("application/x-www-form-urlencoded")){
				//表单数据
				requestWrapper.setParameterStr(decodeBody);
			}
        }
        if(response instanceof HttpServletResponse) {
        	responseWrapper = new MyResponseWrapper((HttpServletResponse) response);
        }
        if(requestWrapper == null || responseWrapper==null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, responseWrapper);
            //修改response 加密返回值
    		String reqBody = responseWrapper.getTextContent();
    		String encodeBody =null;
			try {
				encodeBody = AESUtil.encrypt(reqBody, AESUtil.KEY);
				encodeBody = "{\"data\":\""+encodeBody+"\"}";
			} catch (Exception e) {
				e.printStackTrace();
			}
    		responseWrapper.setContentLength(encodeBody.length());
    		response.getOutputStream().write(encodeBody.getBytes());
        }
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

}
